package com.abkj.platform.tail.controller;

import com.abkj.platform.base.dao.warp.SQLType;
import com.abkj.platform.tail.domain.Displacement;
import com.abkj.platform.tail.domain.JcUser;
import com.abkj.platform.tail.domain.Level;
import com.abkj.platform.tail.domain.Osmometer;
import com.abkj.platform.tail.domain.Rain;
import com.abkj.platform.tail.domain.Ultrasonic;
import com.abkj.platform.tail.service.BaseService;
import com.abkj.platform.tail.service.IAlertService;
import com.abkj.platform.tail.util.Base64Util;
import com.abkj.platform.tail.util.JsonUtils;

import gnu.io.CommPortIdentifier;

import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IndexController extends BaseController {

	@Autowired
	private BaseService baseService;
	@Autowired
	private IAlertService alertService;
	
	private final String SEQ = "ABKJ-TAIL-0001";

	@RequestMapping(value = { "/letsgo" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public String login(String username, String password,
			HttpServletRequest request) {
		String pass = Base64Util.encodePwd(password);
		List ls = this.baseService.findObjectsBySql(JcUser.class,
				"select * from jcuser where username='" + username
						+ "' and password='" + pass + "'");
		if (ls.size() > 0) {
			if (isOverdue()) {
				return "3";
			}

			JcUser user = (JcUser) ls.get(0);
			if (user.getState() == 1) {
				return "2";
			}
			user.setLasttime(new Date());
			setSessionUser(request, user);
			this.baseService.updateObject(user, "lasttime");
			return "0";
		}
		return "1";
	}

	private boolean isOverdue() {
		List map = this.baseService.findBySql("select * from config");
		Map config = (Map) map.get(0);
		String serialNumber = String.valueOf(config.get("auth"));
		if (StringUtils.isEmpty(serialNumber))
			return true;
		try {
			String decode = Base64Util.decodeStr(serialNumber);
			if (decode.indexOf("ABKJ-TAIL-0001") == -1)
				return true;
			String day = decode.replaceAll("ABKJ-TAIL-0001", "");
			long d = Long.parseLong(day) + 2592000000L;
			long now = System.currentTimeMillis();
			if (now > d) {
				return true;
			}
			return false;
		} catch (Exception e) {
		}
		return true;
	}

	@RequestMapping(value = { "/authReset" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public String authReset(HttpServletRequest request, String serio) {
		if (StringUtils.isEmpty(serio))
			return "0";
		try {
			String decode = Base64Util.decodeStr(serio);
			if (decode.indexOf("ABKJ-TAIL-0001") == -1)
				return "0";
			String day = decode.replaceAll("ABKJ-TAIL-0001", "");
			long d = Long.parseLong(day);
			if (System.currentTimeMillis() > d) {
				return "0";
			}
			this.baseService.excuteBySql(SQLType.UPDATE,
					"update config set auth='" + serio + "' where id=1");
			return "1";
		} catch (Exception e) {
		}
		return "0";
	}

	@RequestMapping({ "/auth" })
	@ResponseBody
	public String auth(HttpServletRequest request, String pwd, String newPwd) {
		List map = this.baseService.findBySql("select * from config");
		Map config = (Map) map.get(0);
		Map data = new HashMap();
		data.put("ret", Integer.valueOf(0));
		data.put("day", Integer.valueOf(0));
		if (StringUtils.isEmpty(config.get("auth")))
			return JsonUtils.writeObjToString(data);
		try {
			String decode = Base64Util.decodeStr(String.valueOf(config
					.get("auth")));
			if (decode.indexOf("ABKJ-TAIL-0001") == -1) {
				return JsonUtils.writeObjToString(data);
			}
			String day = decode.replaceAll("ABKJ-TAIL-0001", "");
			long d = Long.parseLong(day);
			long now = System.currentTimeMillis();
			if (now > d) {
				data.put("day", Integer.valueOf(calcDays(d)));
				return JsonUtils.writeObjToString(data);
			}
			data.put("ret", Integer.valueOf(1));
			return JsonUtils.writeObjToString(data);
		} catch (Exception e) {
		}
		return JsonUtils.writeObjToString(data);
	}

	private int calcDays(long day) {
		long now = new Date().getTime();
		long temp = now - day;
		long dd = temp / 86400000L;
		return 30 - (int) dd > 0 ? 30 - (int) dd : 0;
	}

	@RequestMapping({ "/" })
	public String index(ModelMap model) {
		List osmometers = this.baseService.findAllObjects(Osmometer.class);
		List levels = this.baseService.findAllObjects(Level.class);
		List ultrasonics = this.baseService.findAllObjects(Ultrasonic.class);
		List rains = this.baseService.findAllObjects(Rain.class);
		List displacements = this.baseService
				.findAllObjects(Displacement.class);
		List map = this.baseService.findBySql("select * from config");

		String basicQuery = "SELECT * FROM level WHERE TYPE=1 limit 1";
		List mapLevel = this.baseService.findBySql(basicQuery);
		float standardval = 0.0F;
		if ((mapLevel != null) && (mapLevel.size() != 0)) {
			Map basic = (Map) mapLevel.get(0);
			standardval = NumberUtils.toFloat(String.valueOf(basic
					.get("should")));
		}

		model.put("osmometers", JsonUtils.writeObjToString(osmometers)
				.replaceAll("\"", "'"));
		model.put("levels",
				JsonUtils.writeObjToString(levels).replaceAll("\"", "'"));
		model.put("ultrasonics", JsonUtils.writeObjToString(ultrasonics)
				.replaceAll("\"", "'"));
		model.put("rains",
				JsonUtils.writeObjToString(rains).replaceAll("\"", "'"));
		model.put("displacements", JsonUtils.writeObjToString(displacements)
				.replaceAll("\"", "'"));
		model.put("config", map.get(0));
		model.put("standardval", Float.valueOf(standardval));
		Map<String, Object> form = alertService.getForm();
		model.put("able", form.get("able"));
		model.put("minute", form.get("minute"));
		return "/index";
	}

	@RequestMapping({ "/menu" })
	public String menu(HttpServletRequest request) {
		return "/menu";
	}

	@RequestMapping({ "/main" })
	public String main(HttpServletRequest request) {
		return "/main";
	}

	@RequestMapping({ "/map" })
	public String map(HttpServletRequest request) {
		return "/map";
	}

	@RequestMapping({ "/pwd" })
	@ResponseBody
	public String pwd(HttpServletRequest request, String pwd, String newPwd) {
		JcUser user = getSessionUser(request);
		String opwd = Base64Util.encodePwd(pwd);
		if (user.getPassword().equals(opwd)) {
			String npwd = Base64Util.encodePwd(newPwd);
			user.setPassword(npwd);
			this.baseService.updateObject(user, "password");
			createJcUserLog(request, "修改密码", "修改密码！");
			return "0";
		}
		return "1";
	}

	@RequestMapping({ "/logout" })
	public String logout(HttpServletRequest request) {
		removeSessionUser(request);
		return "redirect:login";
	}

	@RequestMapping(value = { "/readConfig" }, produces = { "text/html;charset=UTF-8" })
	@ResponseBody
	public String readConfig() {
		List maps = this.baseService.findBySql("select * from config");
		Map ret = new HashMap();
		Map config = (Map) maps.get(0);

		List coms = new ArrayList();
		try {
			Enumeration portList = CommPortIdentifier.getPortIdentifiers();
			while (portList.hasMoreElements()) {
				CommPortIdentifier portId = (CommPortIdentifier) portList
						.nextElement();
				if (portId.getPortType() == 1) {
					coms.add(portId.getName());
				}
			}
		} catch (Exception localException) {
		}
		ret.put("config", config);
		ret.put("com", coms);
		return JsonUtils.writeObjToString(ret);
	}

	@RequestMapping(value = { "/writeConfig" }, produces = { "text/html;charset=UTF-8" })
	@ResponseBody
	public String writeConfig(String name, String com, int scan, int rate) {
		this.baseService.excuteBySql(SQLType.UPDATE, "update config set name='"
				+ name + "',com='" + com + "',scan=" + scan + ",rate=" + rate
				+ " where id=1");
		return "0";
	}
}